/**
 * 
 */
package org.shark.jdbcTemplateTool.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import org.shark.jdbcTemplateTool.JdbcTemplateTool;
import org.shark.jdbcTemplateTool.dao.BaseDao;
import org.shark.jdbcTemplateTool.exception.NoColumnAnnotationFoundException;
import org.shark.jdbcTemplateTool.exception.NoIdAnnotationFoundException;
import org.shark.jdbcTemplateTool.model.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shark.app.common.exception.DataAccessException;

/**
 * @author lenovo
 * @description
 * @date 2016年8月16日
 */
public class BaseDaoImpl<T, PK extends Serializable>
	implements BaseDao<T, PK> {
	
	private static Logger log = LoggerFactory.getLogger(BaseDaoImpl.class);
	
	protected String sql = "";

	protected Map<String, Object> params = null;

	protected JdbcTemplateTool jtt;
	
	private Class<T> entityClass;

	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {
		this.entityClass = null;
		Type type = getClass().getGenericSuperclass();
		if (type instanceof ParameterizedType) {
			Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
			this.entityClass = (Class<T>) parameterizedType[0];
		}
	}
	
	/**
	 * 根据ID取得数据
	 * @param id
	 * @return
	 */
	public T get(PK id) {
		try {
			return jtt.get(entityClass, id);
		} catch (NoIdAnnotationFoundException | NoColumnAnnotationFoundException e) {
			log.error("Entity 错误。" + entityClass.getName(), e);
		}
		return null;
	}
	
	public Page<T> page(String sql, Object[] params, int currentPage, int pagesize) {
		return jtt.page(sql, params, currentPage, pagesize, entityClass);
	}
	
	/**
	 * 更新数据
	 * @param po
	 * @return
	 */
	public int update(T po) {
		try {
			return jtt.update(po);
		} catch (Exception e) {
			throw new DataAccessException("更新数据出错", e);
		}
	}
	
	/**
	 * 更新数据
	 * @param po
	 * @return
	 */
	public int updateNotNull(T po) {
		try {
			return jtt.updateNotNull(po);
		} catch (Exception e) {
			throw new DataAccessException("更新数据出错", e);
		}
	}
	
	/**
	 * 新增或更新数据
	 * @param po
	 * @return
	 */
	public int save(T po) {
		try {
			return jtt.save(po);
		} catch (Exception e) {
			throw new DataAccessException("保存数据出错", e);
		}
	}
	
	/**
	 * 统计
	 * @param sql
	 * @param params
	 * @return
	 */
	public int count(String sql, Object[] params) {
		return jtt.count(sql, params);
	}
	
	public T getByParam() {
		List<T> ret = jtt.list(sql, params, entityClass);
		if (ret.size() > 0) {
			return ret.get(0);
		} else {
			return null;
		}
	}
	
	public List<T> listByParam() {
		return jtt.list(sql, params, entityClass);
	}
	
	public void setSql(String sql) {
		this.sql = sql;
	}

	public void setParams(Map<String, Object> params) {
		this.params = params;
	}
}